<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\AppBaseController;
use App\Models\Bonus;
use App\Models\IntegralLog;
use App\Models\Role;
use App\Repositories\BonusRepository;
use App\Repositories\UsersRepository;
use App\User;
use Illuminate\Http\Request;
use Flash;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Prettus\Repository\Criteria\RequestCriteria;
use Response;

class UserController extends AppBaseController
{
    /** @var  userRepository */
    private $userRepository;
    private $bonuseRepository;

    public function __construct(UsersRepository $usersRepository, BonusRepository $bonusRepository)
    {
        $this->userRepository = $usersRepository;
        $this->bonuseRepository = $bonusRepository;
    }

    /**
     * Display a listing of the User.
     *
     * @param Request $request
     * @return Response
     */
    public function index(Request $request)
    {

        $model = new User();
        $xcx_openid= request('xcx_openid',false);
        if($xcx_openid){
            $model = $model->where('xcx_openid',$xcx_openid);
        }

        $nickname = request('nickname',false);
        if($nickname){
            $model = $model->where('nickname','like',"%$nickname%");
        }

        $in_blacklist = request('in_blacklist',false);
        if(is_string($in_blacklist) && $in_blacklist!==''){
            $model = $model->where('in_blacklist',$in_blacklist);
        }

        $users = $model->orderBy('id','desc')->paginate(100);
        $users->load('parent');
        return view('users.index')
            ->with('users', $users)->with('request',$request->all());
    }

    public function manageList(Request $request)
    {

        $model = new User();
        $xcx_openid= request('xcx_openid',false);
        if($xcx_openid){
            $model = $model->where('xcx_openid',$xcx_openid);
        }

        $nickname = request('nickname',false);
        if($nickname){
            $model = $model->where('nickname','like',"%$nickname%");
        }

        $in_blacklist = request('in_blacklist',false);
        if(is_string($in_blacklist) && $in_blacklist!==''){
            $model = $model->where('in_blacklist',$in_blacklist);
        }
        $users = $model->orderBy('id','desc')->paginate(100);
        $users->load('parent');
        return view('users.list')
            ->with('users', $users)->with('request',$request->all());
    }

    /**
     * Show the form for creating a new User.
     *
     * @return Response
     */
    public function create()
    {
        return view('users.create');
    }

    /**
     * Store a newly created User in storage.
     *
     * @param CreateUserRequest $request
     *
     * @return Response
     */
    public function store(Request $request)
    {
        $input = $request->all();

        $User = $this->userRepository->create($input);

        Flash::success('User saved successfully.');

        return redirect(route('users.index'));
    }

    /**
     * Display the specified User.
     *
     * @param  int $id
     *
     * @return Response
     */
    public function show($id)
    {
        $User = $this->userRepository->findWithoutFail($id);

        if (empty($User)) {
            Flash::error('User not found');

            return redirect(route('users.index'));
        }

        return view('users.show')->with('user', $User)->with('bonuses',Bonus::where([
            ['use_status',0],
            ['use_end_date','>',date('Y-m-d H:i:s')],
        ])->groupBy('name')->get());
    }

    public function setting()
    {
        $id = request('id',0);
        $User = $this->userRepository->findWithoutFail($id);

        if (empty($User)) {
            Flash::error('User not found');

            return redirect(route('users.list'));
        }
        return view('users.setting')->with('user', $User)->with('bonuses',Bonus::where([
            ['use_status',0],
            ['use_end_date','>',date('Y-m-d H:i:s')],
        ])->groupBy('name')->get())->with('roles',Role::where([
            ['status',1],
        ])->get());
    }

    public function addBonus()
    {
        $bonuse = Bonus::find(request('bonus_id'));
        $user_id = request('user_id');
        $this->bonuseRepository->dispatch($bonuse->name,$user_id);

        $User = $this->userRepository->findWithoutFail($user_id);
        return redirect(route('users.setting',['id'=>$user_id]));
    }

    public function addRole()
    {
        $role = Role::find(request('role_id'));
        $user_id = request('user_id');
        $User = $this->userRepository->findWithoutFail($user_id);
        $User->roles()->sync(request('role_id'));
        Flash::success('User updated successfully.');
        return redirect(route('users.setting',['id'=>$user_id]));
    }

    /**
     * Show the form for editing the specified User.
     *
     * @param  int $id
     *
     * @return Response
     */
    public function edit($id)
    {
        $User = $this->userRepository->findWithoutFail($id);

        if (empty($User)) {
            Flash::error('User not found');

            return redirect(route('users.index'));
        }

        return view('users.edit')->with('user', $User);
    }

    /**
     * Update the specified User in storage.
     *
     * @param  int              $id
     * @param UpdateUserRequest $request
     *
     * @return Response
     */
    public function update($id, Request $request)
    {
        $User = $this->userRepository->findWithoutFail($id);
        if (empty($User)) {
            Flash::error('User not found');

            return redirect(route('users.setting'));
        }
        $input = $request->all();
        if($input['integral']){
            $input['integral'] = $input['integral']>0?$input['integral']:0;
        }
        if($input['password'])
            $input['password'] = bcrypt($input['password']);
        if($input['integral']!=$User['integral']){
            IntegralLog::create([
                'user_id'=>$User->id,
                'type'=>1,
                'add_type'=>3,
                'junior_id'=>0,
                'admin_id'=>Auth::guard('admin')->id(),
                'title'=>'后台修改菜金',
                'amount'=>$User['integral'],
                'calculate'=>$input['integral'],
            ]);
        }
        $User = $this->userRepository->update($input, $id);

        Flash::success('User updated successfully.');

        return redirect(route('users.list'));
    }

    /**
     * Remove the specified User from storage.
     *
     * @param  int $id
     *
     * @return Response
     */
    public function destroy($id)
    {
        $User = $this->userRepository->findWithoutFail($id);

        if (empty($User)) {
            Flash::error('User not found');

            return redirect(route('users.index'));
        }

        $this->userRepository->delete($id);

        Flash::success('User deleted successfully.');

        return redirect(route('users.index'));
    }

    public function juniorDel()
    {
        $id = request('id');
        $user = User::find($id);
        $parent_id = $user->parent_id;
        $user->parent_id = 0;
        $user->save();

        $User = User::find($parent_id);
        Flash::success('User updated successfully.');
        return redirect(route('users.setting',['id'=>$user->id]));
    }

    public function delRole()
    {
        $role_id = request('role_id');
        $user_id = request('user_id');
        DB::table('role_user')->where('user_id',$user_id)->where('role_id',$role_id)->delete();

        $user = User::find($user_id);
        Flash::success('User updated successfully.');
        return redirect(route('users.setting',['id'=>$user->id]));
    }
}
